﻿using BPMS.Business;
using BPMS.Entity;
using BPMS.IBusiness;
using DotNet.Kernel;
using DotNet.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace BPMS.MVC.Controllers
{
    public class UserController : BaseController
    {
        BPMS_OrganizationIBLL bpms_organizationibll = new BPMS_OrganizationBLL();
        BPMS_PermissionIBLL bpms_permissionibll = new BPMS_PermissionBLL();
        BPMS_UserRoleIBLL bpms_userroleibll = new BPMS_UserRoleBLL();
        BPMS_UserIBLL bpms_useribll = new BPMS_UserBLL();
        BPMS_User bpms_user = new BPMS_User();

        #region 用户列表
        /// <summary>
        /// 用户列表
        /// </summary>
        /// <returns></returns>
        public ActionResult UserList()
        {
            return View();
        }
        /// <summary>
        /// 处理方式
        /// </summary>
        public void LoadAction()
        {
            string active = Request["action"];                                          //提交类型
            int pageIndex = CommonHelper.GetInt(Request["pqGrid_PageIndex"]);           //当前页
            int pageSize = CommonHelper.GetInt(Request["pqGrid_PageSize"]);             //当前页大小
            string orderField = Request["pqGrid_OrderField"];                           //排序字段  
            string orderType = Request["pqGrid_OrderType"];                             //排序类型
            string pqGrid_Sort = Request["pqGrid_Sort"];                                //要显示字段
            string key = Request["key"];                                                //主键
            string Parm_Key_Value = Request["Parm_Key_Value"];                          //搜索条件键值
            string search = Request["search"];                                          //模糊查询条件
            switch (active)
            {
                case "GridBindList":                                                    //加载用户列表
                    int count = 0;
                    Hashtable parm = HashtableHelper.String_Key_ValueToHashtable(Parm_Key_Value);
                    Response.Write(JsonHelper.PqGridPageJson<BPMS_User>(bpms_useribll.GetPageList(parm, orderField, orderType, pageIndex, pageSize, ref count), pageIndex, pqGrid_Sort, count));
                    Response.End();
                    break;
                case "Delete":                                                          //删除用户数据
                    string UserId = SessionHelper.GetSessionUser().UserId;
                    if (key == UserId)
                    {
                        Response.Write(string.Format(MessageHelper.MSG0018, SessionHelper.GetSessionUser().Account));
                        Response.End();
                    }
                    Response.Write(bpms_useribll.Delete(key).ToString());
                    Response.End();
                    break;
                case "autocomplete":                                                    //用户自动补全，返回JSON
                    Response.Write(JsonHelper.ListToJson<BPMS_User>(bpms_useribll.autocomplete(search), "JSON"));
                    Response.End();
                    break;
                case "derive"://导出Excel
                    string[] DataColumn = { "编号:Code", "登录账户:Account", "真实姓名:RealName", "性别:Gender", "手机号码:Mobile", "QQ号码:OICQ", "电子邮件:Email", "岗位:Duty", "职称:Title", "部门名称:DepartmentName", "有效:Enabled", "说明:Description" };
                    ExcelHelper.ExportExcel<BPMS_User>(bpms_useribll.GetList(), DataColumn, "用户信息-" + DateTime.Now.ToString("yyyy-MM-dd"));
                    break;
                default:
                    break;
            }
        }
        #endregion

        #region 用户表单
        /// <summary>
        /// 用户表单
        /// </summary>
        /// <returns></returns>
        public ActionResult UserForm()
        {
            return View();
        }
        /// <summary>
        /// 确认事件
        /// </summary>
        /// <param name="bpms_user">用户信息</param>
        /// <returns></returns>
        public ActionResult AcceptClick(BPMS_User bpms_user)
        {
            string key = Request["key"];                                                //主键
            bool IsOk = false;
            bpms_user.Spell = PinyinHelper.PinyinString(bpms_user.RealName);
            if (!string.IsNullOrEmpty(key))//判断是否编辑
            {
                bpms_user.UserId = key;
                bpms_user.ModifyDate = DateTime.Now;
                bpms_user.ModifyUserId = SessionHelper.GetSessionUser().UserId;
                bpms_user.ModifyUserName = SessionHelper.GetSessionUser().UserName;
                bpms_user.Password = null;
                IsOk = bpms_useribll.Update(bpms_user);
            }
            else
            {
                bpms_user.UserId = CommonHelper.GetGuid;
                bpms_user.Secretkey = Md5Helper.MD5(CommonHelper.CreateNo(), 16);
                string Password = DESEncrypt.Encrypt(bpms_user.Password, bpms_user.Secretkey);
                bpms_user.Password = Md5Helper.MD5(Password, 32);
                bpms_user.CreateUserId = SessionHelper.GetSessionUser().UserId;
                bpms_user.CreateUserName = SessionHelper.GetSessionUser().UserName;
                IsOk = bpms_useribll.Insert(bpms_user);
            }
            return Content(IsOk.ToString().ToLower());
        }
        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        /// <param name="key">主键</param>
        /// <returns></returns>
        public ActionResult InitControl(string key)
        {
            if (!string.IsNullOrEmpty(key))
            {
                bpms_user = bpms_useribll.GetEntity(key);
                return Content(JsonHelper.ObjectToJson(bpms_user));
            }
            return null;
        }
        /// <summary>
        /// 初始化绑定下拉框 数据字典
        /// </summary>
        public ActionResult InitBindDrop()
        {
            BPMS_ItemDetailsIBLL bpms_itemdetailsibll = new BPMS_ItemDetailsBLL();
            return Content(JsonHelper.DropToJson<BPMS_ItemDetails>(bpms_itemdetailsibll.GetList(), "JSON"));
        }
        #endregion

        #region 用户详细信息
        /// <summary>
        /// 用户详细信息
        /// </summary>
        /// <returns></returns>
        public ActionResult UserInfo()
        {
            return View();
        }
        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        /// <param name="key">主键</param>
        /// <returns></returns>
        public ActionResult InitControlUserInfo(string key)
        {
            if (!string.IsNullOrEmpty(key))
            {
                foreach (BPMS_User item in bpms_useribll.GetIListById(key))
                {
                    return Content(JsonHelper.ObjectToJson(item));
                }
            }
            return null;
        }
        /// <summary>
        /// 拥有权限列表
        /// </summary>
        public ActionResult GetPermissionTree(string key)
        {
            StringBuilder PermissionTree = new StringBuilder();
            IList list = bpms_permissionibll.GetModulePermission(key);
            IList listButton = bpms_permissionibll.GetButtonPermission(key);
            int eRowIndex = 0;
            foreach (BPMS_ModulePermission entity in list)
            {
                if (entity.ParentId == "0")
                {
                    string trID = "node-" + eRowIndex.ToString();
                    PermissionTree.Append("<tr id='" + trID + "'>");
                    PermissionTree.Append("<td style='width: 230px;padding-left:20px;'><img src='/Themes/images/32/" + entity.Img + "' style='width:20px; height:20px;vertical-align: middle;' alt=''/><span style='padding-left:8px;'>" + entity.FullName + "</span></td>");
                    PermissionTree.Append("<td>" + entity.Description + "</td>");
                    PermissionTree.Append("</tr>");
                    //创建子节点
                    PermissionTree.Append(GetTableTreeNode(entity.MenuId, list, trID, listButton));
                    eRowIndex++;
                }
            }
            if (eRowIndex == 0)
            {
                PermissionTree.Append("<tr><td colspan='2' style=\"text-align: left;color:Red\">没有找到您要的相关数据...</td></tr>");
            }
            return Content(PermissionTree.ToString());
        }
        /// <summary>
        /// 创建子节点
        /// </summary>
        /// <param name="ParentId">父节点主键</param>
        /// <param name="list">菜单集合</param>
        /// <param name="listButton">按钮集合</param>
        /// <returns></returns>
        public string GetTableTreeNode(string ParentId, IList list, string parentTRID, IList listButton)
        {
            StringBuilder sb_TreeNode = new StringBuilder();
            int i = 1;
            foreach (BPMS_ModulePermission entity in list)
            {
                if (entity.ParentId == ParentId)
                {
                    string trID = parentTRID + "-" + i.ToString();
                    sb_TreeNode.Append("<tr id='" + trID + "' class='child-of-" + parentTRID + "'>");
                    sb_TreeNode.Append("<td style='padding-left:20px;'><img src='/Themes/images/32/" + entity.Img + "' style='width:20px; height:20px;vertical-align: middle;' alt=''/><span style='padding-left:8px;'>" + entity.FullName + "</span></td>");
                    sb_TreeNode.Append("<td>" + entity.Description + "</td>");
                    sb_TreeNode.Append("</tr>");
                    //创建子节点
                    sb_TreeNode.Append(GetTableTreeNode(entity.MenuId, list, trID, listButton));
                    //创建操作按钮
                    sb_TreeNode.Append(Button(entity.MenuId, listButton, trID));
                    i++;
                }
            }
            return sb_TreeNode.ToString();
        }
        /// <summary>
        /// 加载权限操作按钮
        /// </summary>
        /// <param name="ParentId"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public string Button(string ParentId, IList list, string parentTRID)
        {
            StringBuilder sb_Button = new StringBuilder();
            int i = 1;
            foreach (BPMS_ButtonPermission entity in list)
            {
                if (entity.MenuId == ParentId)
                {
                    string trID = parentTRID + "-" + i.ToString();
                    sb_Button.Append("<tr hide='true' id='" + trID + "' class='child-of-" + parentTRID + "'>");
                    sb_Button.Append("<td style='padding-left:20px;'><img src='/Themes/images/16/" + entity.Img + "' style='width:16px; height:16px;vertical-align: middle;' alt=''/><span style='padding-left:8px;'>" + entity.FullName + " - 按钮</span></td>");
                    sb_Button.Append("<td>" + entity.Description + "</td>");
                    sb_Button.Append("</tr>");
                    i++;
                }
            }
            return sb_Button.ToString();
        }

        /// <summary>
        /// 拥有角色
        /// </summary>
        public ActionResult GetRoleList(string key)
        {
            StringBuilder sb_RoleList = new StringBuilder();
            IList list = bpms_userroleibll.GetUserRoleListByUserId(key);
            int eRowIndex = 0;
            foreach (BPMS_Roles entity in list)
            {
                sb_RoleList.Append("<tr>");
                sb_RoleList.Append("<td style='width: 200px;'>" + entity.FullName + "</span></td>");
                sb_RoleList.Append("<td style=\"width: 100px; text-align: center;\">" + entity.Code + "</td>");
                sb_RoleList.Append("<td style=\"width: 100px; text-align: center;\">" + entity.Category + "</td>");
                sb_RoleList.Append("<td>" + entity.Description + "</td>");
                sb_RoleList.Append("</tr>");
                eRowIndex++;
            }
            if (eRowIndex == 0)
            {
                sb_RoleList.Append("<tr><td colspan='4' style=\"text-align: left;color:Red\">没有找到您要的相关数据...</td></tr>");
            }
            return Content(sb_RoleList.ToString());
        }
        #endregion

        #region 重新设置新密码
        /// <summary>
        /// 重新设置新密码
        /// </summary>
        public ActionResult UpdateUserPwd()
        {
            return View();
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="Account">账户</param>
        /// <param name="key">主键</param>
        /// <param name="code">验证码</param>
        /// <param name="pwd">密码</param>
        /// <returns></returns>
        public ActionResult AcceptUpdateUserPwd(string Account, string key, string code, string pwd)
        {
            string s = Session["dt_session_code"].ToString().ToLower();
            if (code.ToLower() != Session["dt_session_code"].ToString().ToLower())
            {
                return Content(MessageHelper.MSG0026);
            }
            bool IsOk = false;
            if (Account != "System" && Account != "admin")
            {
                bpms_user = bpms_useribll.GetEntity(key);
                string Password = DESEncrypt.Encrypt(pwd, bpms_user.Secretkey);
                bpms_user.Password = Md5Helper.MD5(Password, 32);
                bpms_user.ModifyDate = DateTime.Now;
                bpms_user.ModifyUserId = SessionHelper.GetSessionUser().UserId;
                bpms_user.ModifyUserName = SessionHelper.GetSessionUser().UserName;
                IsOk = bpms_useribll.Update(bpms_user);
                if (IsOk)
                {
                    if (Request["status"] == "1")
                    {
                        Session.Abandon();  //取消当前会话
                        Session.Clear();    //清除当前浏览器所以Session
                        Response.Write("<script>alert('登陆修改成功,请重新登陆');top.location.href='/Index.htm'</script>");
                    }
                    else
                    {
                        return Content("success");
                    }
                }
                else
                {
                    return Content(MessageHelper.MSG0022);
                }
            }
            else
            {
                return Content(Account + "用户不能被修改。");
            }
            return null;
        }
        #endregion

        #region 用户分配角色
        /// <summary>
        /// 用户分配角色
        /// </summary>
        /// <returns></returns>
        public ActionResult UserRole()
        {
            ViewBag.strUserInfo = Server.UrlDecode(Request["RealName"]);//用户信息
            return View();
        }
        /// <summary>
        /// 保存事件
        /// </summary>
        /// <param name="item">值</param>
        /// <returns></returns>
        public ActionResult AcceptClick_UserRole(string item)
        {
            string UserId = Request["UserId"];
            string[] array = new string[0];
            if (!string.IsNullOrEmpty(item))
            {
                array = item.Split('≌');
            }
            bool IsOk = false;
            string CreateUserId = SessionHelper.GetSessionUser().UserId;
            string CreateUserName = SessionHelper.GetSessionUser().UserName;
            IsOk = bpms_userroleibll.BatchAddUserRole(array, UserId, CreateUserId, CreateUserName);
            return Content(IsOk.ToString().ToLower());
        }
        /// <summary>
        /// 组织机构
        /// </summary>
        public ActionResult GetTree_UserRole()
        {
            StringBuilder sbCompany = new StringBuilder();
            IList list = bpms_organizationibll.GetList();
            List<BPMS_Organization> itemNode = IListHelper.IListToList<BPMS_Organization>(list).FindAll(t => t.ParentId == "0");
            foreach (BPMS_Organization entity in itemNode)
            {
                sbCompany.Append("<li>");
                sbCompany.Append("<div id='" + entity.OrganizationId + "'><img src='/Themes/images/16/house.png' style='vertical-align: middle;' alt=''/>" + entity.FullName + "</div>");
                //创建子节点
                sbCompany.Append(GetTreeNode(list));
                sbCompany.Append("</li>");
            }
            return Content(sbCompany.ToString());
        }
        /// <summary>
        /// 创建子节点
        /// </summary>
        /// <param name="list">list</param>
        /// <param name="dt">list</param>
        /// <returns></returns>
        public string GetTreeNode(IList list)
        {
            StringBuilder sb_TreeNode = new StringBuilder();
            List<BPMS_Organization> itemNode = IListHelper.IListToList<BPMS_Organization>(list).FindAll(t => t.Category == "公司");
            int index = 0;
            string strclass = "";
            if (itemNode.Count > 0)
            {
                sb_TreeNode.Append("<ul>");
                foreach (BPMS_Organization entity in itemNode)
                {
                    if (index == 0)
                        strclass = "collapsableselected";
                    else
                        strclass = "";
                    sb_TreeNode.Append("<li>");
                    sb_TreeNode.Append("<div class='" + strclass + "' id='" + entity.OrganizationId + "'><img src='/Themes/images/16/chart_organisation.png' style='vertical-align: middle;' alt=''/>" + entity.FullName + "</div>");
                    sb_TreeNode.Append("</li>");
                    index++;
                }
                sb_TreeNode.Append("</ul>");
            }
            return sb_TreeNode.ToString();
        }
        /// <summary>
        /// 加载角色
        /// </summary>
        /// <param name="DepartmentId"></param>
        public ActionResult GetNodeRole(string OrganizationId, string UserId)
        {
            DataTable RoleList = bpms_userroleibll.GetUserRoleList(UserId);
            StringBuilder sbRole = new StringBuilder();
            DataView dv = new DataView(RoleList);
            dv.RowFilter = " OrganizationId = '" + OrganizationId + "'";
            sbRole.Append("<div id='Role_" + OrganizationId + "' class='UserRole'>");
            if (dv.Count > 0)
            {
                foreach (DataRowView drv in dv)
                {
                    string checkbuttonNo = "checkbuttonNo";
                    string triangleNo = "triangleNo";
                    string IsExist = drv["IsExist"].ToString();
                    if (!string.IsNullOrEmpty(IsExist))
                    {
                        checkbuttonNo = "checkbuttonOk";
                        triangleNo = "triangleOk";
                    }
                    sbRole.Append("<div class=\"" + checkbuttonNo + "  panelcheck\">");
                    sbRole.Append("<div id=\"" + drv["RoleId"] + "\" class=\"checktext\">");
                    sbRole.Append("<img src=\"../../Themes/Images/16/AllotRole.png\" />" + drv["FullName"] + "");
                    sbRole.Append("</div>");
                    sbRole.Append("<div class=\"" + triangleNo + "\"></div>");
                    sbRole.Append("</div>");
                }
            }
            else
            {
                sbRole.Append(" <span style='color:red;'>暂无角色</span>");
            }
            sbRole.Append("</div>");
            return Content(sbRole.ToString());
        }
        #endregion
    }
}
